package org.databandtech.mockmq;

import java.util.Properties;
import java.util.concurrent.ExecutionException;

import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.RecordMetadata;

/**
 * 消息生产
 */
public class KafkaProducer {

	final static String HOST="192.168.13.52:9092";//"192.168.10.60:9092"
	final static String TOPIC="Hello-Kafka";
	final static int COUNT=10;    //发送的数据条数
	final static int PARTITION=0; //分区
	

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		Properties properties = new Properties();
		properties.put("bootstrap.servers", HOST);
		// 0:producer不会等待broker发送ack
        // 1:当leader接收到消息后发送ack
        // -1:当所有的follower都同步消息成功后发送ack
		properties.put("acks", "-1");
		properties.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
		properties.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");

		@SuppressWarnings("resource")
		org.apache.kafka.clients.producer.KafkaProducer<String, String> kafkaProducer = new org.apache.kafka.clients.producer.KafkaProducer<String, String>(properties);
		// -- 同步发送消息
		for (int i = 1; i <= COUNT; i++) {
			RecordMetadata metadata = null;
		    //参数1：topic名, 参数2：消息文本； ProducerRecord多个重载的构造方法
			String msg = org.databandtech.common.Mock.getChineseName()+","+Mock.getDate()+","+
					Mock.getEmail(4, 6)+","+Mock.getNumString(90)+","+
					Mock.getNumString(50)+","+Mock.getNumString(300);

			//指定分区发送
			//ProducerRecord<String, String> pr = new ProducerRecord<String, String>(TOPIC,PARTITION,"key"+i, msg +"--"+i);
			//发送到默认分区
			ProducerRecord<String, String> pr = new ProducerRecord<String, String>(TOPIC, msg +"--"+i);
			try {
				metadata = kafkaProducer.send(pr).get();
				System.out.println("TopicName : " + metadata.topic() + " Partiton : " + metadata
	                    .partition() + " Offset : " + metadata.offset()+"--"+msg+i);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ExecutionException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}		    
		}
	}

}
